package net.documentshare.docu;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.documentshare.docu.corpus.CorpusAttention;
import net.documentshare.docu.corpus.CorpusBean;
import net.documentshare.docu.corpus.CorpusLuceneManager;
import net.documentshare.docu.corpus.CorpusOfDocBean;
import net.documentshare.i.ICommonBeanAware;
import net.documentshare.impl.AItSiteAppclicationModule;
import net.documentshare.impl.AbstractAttention;
import net.documentshare.utils.ItSiteUtil;
import net.simpleframework.ado.db.ExpressionValue;
import net.simpleframework.ado.db.IQueryEntitySet;
import net.simpleframework.ado.db.ITableEntityManager;
import net.simpleframework.ado.db.SQLValue;
import net.simpleframework.ado.lucene.AbstractLuceneManager;
import net.simpleframework.content.EContentStatus;
import net.simpleframework.core.ExecutorRunnable;
import net.simpleframework.core.IInitializer;
import net.simpleframework.core.ITaskExecutorAware;
import net.simpleframework.core.ado.db.Table;
import net.simpleframework.core.bean.IIdBeanAware;
import net.simpleframework.core.bean.ITreeBeanAware;
import net.simpleframework.util.ConvertUtils;
import net.simpleframework.util.DateUtils;
import net.simpleframework.util.IoUtils;
import net.simpleframework.util.StringUtils;
import net.simpleframework.web.WebUtils;
import net.simpleframework.web.page.IPageConstants;
import net.simpleframework.web.page.PageRequestResponse;
import net.simpleframework.web.page.component.AbstractComponentBean;
import net.simpleframework.web.page.component.ComponentParameter;
import net.simpleframework.web.page.component.ui.tabs.EMatchMethod;
import net.simpleframework.web.page.component.ui.tabs.TabHref;
import net.simpleframework.web.page.component.ui.tabs.TabsUtils;

public class DocuApplicationModule extends AItSiteAppclicationModule implements IDocuApplicationModule {
	private String deployName = "docu";

	@Override
	public void init(IInitializer initializer) {
		try {
			super.init(initializer);
			doInit(DocuUtils.class, deployName);
			final ITableEntityManager tMgr = getDataObjectManager();
			DocuUtils.setDocuCounter(tMgr.getCount(new SQLValue("select count(id) from " + tMgr.getTablename() + " where status=?",
					new Object[] { EContentStatus.publish })));
			((ITaskExecutorAware) getApplication()).getTaskExecutor().addScheduledTask(60 * 10, DateUtils.DAY_PERIOD, new ExecutorRunnable() {
				@Override
				public void task() {
					DocuUtils.doStatRebuild();
				}
			});
		} catch (Exception e) {
		}
	}

	@Override
	public String getViewUrl(Object id) {
		final StringBuilder sb = new StringBuilder();
		sb.append("/docu").append("/").append(id);
		sb.append(".html");
		return sb.toString();
	}

	@Override
	public Class<? extends IIdBeanAware> getEntityBeanClass() {
		return DocuBean.class;
	}

	public static final Table docu_documentshare = new Table("it_docu_documentshare");
	public static final Table docu_catalog = new Table("it_docu_catalog");
	public static final Table docu_catalog_temp = new Table("it_docu_catalog_temp");
	public static final Table code_catalog = new Table("it_docu_code_catalog");
	public static final Table code_catalog_temp = new Table("it_docu_code_catalog_temp");
	public static final Table docu_remark = new Table("it_docu_remark");
	public static final Table guestbook_remark = new Table("it_guestbook_remark");
	public static final Table docu_attention = new Table("it_docu_attention");
	public static final Table docu_user = new Table("it_docu_user");
	public static final Table docu_log = new Table("it_docu_log");
	public static final Table docu_favorite = new Table("it_docu_favorite");
	public static final Table docu_Corpus = new Table("it_docu_Corpus");
	public static final Table docu_CorpusOfDoc = new Table("it_docu_CorpusOfdoc");
	public static final Table corpus_attention = new Table("it_corpus_attention");
	public static final Table docu_dellog = new Table("it_docu_dellog");

	@Override
	protected void putTables(Map<Class<?>, Table> tables) {
		super.putTables(tables);
		tables.put(DocuBean.class, docu_documentshare);
		tables.put(DocuCatalog.class, docu_catalog);
		tables.put(DocuCatalogTemp.class, docu_catalog_temp);
		tables.put(DocuCodeCatalog.class, code_catalog);
		tables.put(DocuCodeCatalogTemp.class, code_catalog_temp);
		tables.put(DocuRemark.class, docu_remark);
		tables.put(GuestbookRemark.class, guestbook_remark);
		tables.put(DocuAttention.class, docu_attention);
		tables.put(DocuUserBean.class, docu_user);
		tables.put(DocuLogBean.class, docu_log);
		tables.put(CorpusBean.class, docu_Corpus);
		tables.put(CorpusOfDocBean.class, docu_CorpusOfDoc);
		tables.put(CorpusAttention.class, corpus_attention);
		tables.put(DocuDelLog.class, docu_dellog);
	}

	@Override
	public AbstractComponentBean getComponentBean(PageRequestResponse requestResponse) {
		return null;
	}

	@Override
	protected String getParameters(PageRequestResponse requestResponse) {
		final String s = StringUtils.text(requestResponse.getRequestParameter("s"), "docu");
		return "s=" + s;
	}

	public String tabs13(PageRequestResponse requestResponse) {
		final StringBuffer buf = new StringBuffer();
		final int s = ConvertUtils.toInt(requestResponse.getRequestParameter("s"), 0);
		final int od = ConvertUtils.toInt(requestResponse.getRequestParameter("od"), 0);
		final int catalogId = ConvertUtils.toInt(requestResponse.getRequestParameter("catalogId"), 0);
		int i = 0;
		final EDocuType2[] type2s = EDocuType2.values();
		for (final EDocuType2 type2 : type2s) {
			buf.append("<a hidefocus=\"hidefocus\"");
			buf.append(" href=\"" + DocuUtils.getApplicationUrl(0, s, type2.ordinal(), catalogId) + "\"");
			if (type2.ordinal() == od) {
				buf.append(" class=\"a2 nav_arrow\"");
			}
			buf.append(">").append(type2.toString()).append("</a>");
			if (i++ != type2s.length - 1) {
				buf.append("<span style=\"margin: 0px 4px;\">|</span>");
			}
		}
		return buf.toString();
	}

	@Override
	public String tabs(PageRequestResponse requestResponse) {
		final List<TabHref> tabHrefs = new ArrayList<TabHref>();
		final EDocuType1[] type1s = EDocuType1.values();
		TabHref href = null;
		final int catalogId = ConvertUtils.toInt(requestResponse.getRequestParameter("catalogId"), 0);
		for (final EDocuType1 type1 : type1s) {
			if (type1.isManager()) {
				if (ItSiteUtil.isManage(requestResponse, DocuUtils.applicationModule)) {
					href = new TabHref(type1.toString(), WebUtils.addParameters(DocuUtils.getApplicationUrl(type1.ordinal(), 0, 0, catalogId),
							type1.params()));
					href.setMatchMethod(EMatchMethod.startsWith);
					tabHrefs.add(href);
				}
			} else {
				href = new TabHref(type1.toString(), WebUtils.addParameters(DocuUtils.getApplicationUrl(type1.ordinal(), 0, 0, catalogId),
						type1.params()));
				href.setMatchMethod(EMatchMethod.startsWith);
				tabHrefs.add(href);
			}
		}
		return TabsUtils.tabs(requestResponse, tabHrefs.toArray(new TabHref[tabHrefs.size()]));
	}

	@Override
	public String tabs2(PageRequestResponse requestResponse) {
		final StringBuffer buf = new StringBuffer();
		final int s = ConvertUtils.toInt(requestResponse.getRequestParameter("s"), 0);
		final int od = ConvertUtils.toInt(requestResponse.getRequestParameter("od"), 0);
		int i = 0;
		final Map<Integer, String> dataMap = EDocuFunction.functionMap();
		int size = dataMap.size();
		final int catalogId = ConvertUtils.toInt(requestResponse.getRequestParameter("catalogId"), 0);
		for (final Integer docu : dataMap.keySet()) {
			buf.append("<a hidefocus=\"hidefocus\"");
			buf.append(" href=\"" + DocuUtils.getApplicationUrl(0, docu, od, catalogId) + "\"");
			if (docu == s) {
				buf.append(" class=\"a2 nav_arrow\"");
			}
			buf.append(">").append(dataMap.get(docu)).append("</a>");
			if (i++ != size - 1) {
				buf.append("<span style=\"margin: 0px 4px;\">|</span>");
			}
		}
		return buf.toString();
	}

	@Override
	public String getApplicationUrl(PageRequestResponse requestResponse) {
		return "/docu.html";
	}

	@Override
	public String getDeployPath() {
		return null;
	}

	@Override
	public ITableEntityManager getDataObjectManager() {
		return super.getDataObjectManager(DocuBean.class);
	}

	@Override
	public DocuBean getViewDocuBean(PageRequestResponse requestResponse) {
		final DocuBean docuBean = getBean(DocuBean.class, requestResponse.getRequestParameter(DocuUtils.docuId));
		try {
			long views = docuBean.getViews();
			ICommonBeanAware.Utils.updateViews(requestResponse, getDataObjectManager(), docuBean);
			if (views != docuBean.getViews()) {
				//添加全文索引
				DocuUtils.applicationModule.createLuceneManager(new ComponentParameter(requestResponse.request, requestResponse.response, null))
						.objects2DocumentsBackground(docuBean);
			}
		} catch (final Exception e) {
		}
		return docuBean;
	}

	@Override
	public IQueryEntitySet<DocuCatalog> queryCatalogs(PageRequestResponse requestResponse, ITreeBeanAware parent) {
		final ITableEntityManager catalog_mgr = getDataObjectManager(DocuCatalog.class);
		final StringBuilder sql = new StringBuilder();
		final ArrayList<Object> al = new ArrayList<Object>();
		if (parent == null) {
			sql.append(Table.nullExpr(catalog_mgr.getTable(), "parentid"));
		} else {
			sql.append("parentid=?");
			al.add(parent.getId());
		}
		sql.append(" order by oorder desc");
		return catalog_mgr.query(new ExpressionValue(sql.toString(), al.toArray()), DocuCatalog.class);
	}

	@Override
	public IQueryEntitySet<DocuCatalog> queryCatalogs(Object catalogId) {
		final ITableEntityManager catalog_mgr = getDataObjectManager(DocuCatalog.class);
		final StringBuilder sql = new StringBuilder();
		final ArrayList<Object> al = new ArrayList<Object>();
		if (catalogId == null) {
			sql.append(Table.nullExpr(catalog_mgr.getTable(), "parentid"));
		} else {
			sql.append("parentid=?");
			al.add(catalogId);
		}
		sql.append(" order by oorder desc");
		return catalog_mgr.query(new ExpressionValue(sql.toString(), al.toArray()), DocuCatalog.class);
	}

	@Override
	public IQueryEntitySet<DocuCodeCatalog> queryCodeCatalogs(Object catalogId) {
		final ITableEntityManager catalog_mgr = getDataObjectManager(DocuCodeCatalog.class);
		final StringBuilder sql = new StringBuilder();
		final ArrayList<Object> al = new ArrayList<Object>();
		if (catalogId == null) {
			sql.append(Table.nullExpr(catalog_mgr.getTable(), "parentid"));
		} else {
			sql.append("parentid=?");
			al.add(catalogId);
		}
		sql.append(" order by oorder desc");
		return catalog_mgr.query(new ExpressionValue(sql.toString(), al.toArray()), DocuCodeCatalog.class);
	}

	@Override
	public AbstractLuceneManager createLuceneManager(final ComponentParameter compParameter) {
		final File iPath = new File(compParameter.getServletContext().getRealPath(IPageConstants.DATA_HOME + "/" + "docu_index"));
		IoUtils.createDirectoryRecursively(iPath);
		return new DocuLuceneManager(compParameter, iPath);
	}

	@Override
	public AbstractAttention getAttention(Object userId, Object id) {
		final ITableEntityManager tMgr = getDataObjectManager(DocuAttention.class);
		return tMgr.queryForObject(new ExpressionValue("userId=? and docuId=?", new Object[] { userId, id }), DocuAttention.class);
	}

	@Override
	public AbstractLuceneManager createCorpusLuceneManager(ComponentParameter compParameter) {
		final File iPath = new File(compParameter.getServletContext().getRealPath(IPageConstants.DATA_HOME + "/" + "corpus_index"));
		IoUtils.createDirectoryRecursively(iPath);
		return new CorpusLuceneManager(compParameter, iPath);
	}
}
